package com.cxs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cxs.dto.FileUploadDTO;
import com.cxs.model.SysFile;
import com.cxs.service.FileUploadService;
import com.cxs.service.SysFileService;
import com.cxs.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/*
 * @Project:file-upload-senior
 * @Author:cxs
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@RestController
public class FileController {

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private FileUploadService fileUploadService;

    @GetMapping("/hello")
    public Result hello(){
        return Result.success("hello");
    }

    @PostMapping("/upload")
    public Result upload(FileUploadDTO dto){
        if (ObjectUtils.isEmpty(dto)) {
            return Result.error("入参错误，文件上传失败");
        }
        Result result = Result.success("文件上传成功");
        if (dto.getChunkFlag()) {
            fileUploadService.chunkFileUpload(dto, result);
        } else {
            fileUploadService.singleFileUpload(dto, result);
        }
        return result;
    }

    @GetMapping("/checkFileExist")
    public Result checkFileExist(@RequestParam(value = "fileMd5Id", required = true) String fileMd5Id){
        // 根据fileMd5Id查询文件是否存在
        LambdaQueryWrapper<SysFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysFile::getFileMd5, fileMd5Id.trim());
        SysFile one = sysFileService.getOne(wrapper);
        return Result.success(null != one);
    }
}
